﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using DAL;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.HSSF.Util;
using System.IO;
using Facade.Excel;
using Coolite.Ext.Web;
using NPOI;
using NPOI.SS.UserModel;
using System.Reflection;
using ZedGraph;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections;

namespace PeisongWeb.admin
{
    public partial class complaintlist : adminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("DM", 1))
                {
                    rptBind();
                    ddlctNameBind();
                    ddlBuyerBind();
                    ddlSellerBind();
                    ddlDepartmentBind();
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                    return;
                }
            }

        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            rptBind();
        }
        private string strWhere()
        {
            StringBuilder where = new StringBuilder();
            where.Append("1=1");
            if (ext_StartInputDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,CONVERT(DATETIME,a.complaintDt),'{0}')<=0", ext_StartInputDt.Value.ToString());
            if (ext_EndInputDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,CONVERT(DATETIME,a.complaintDt),'{0}')>=0", ext_EndInputDt.Value.ToString());
            if (ddl_buyer.SelectedValue != "")
                where.AppendFormat(" and a.buyerid={0}", Convert.ToInt32(ddl_buyer.SelectedValue));
            if (ddl_ctype.SelectedValue != "")
                where.AppendFormat(" and a.ctId={0}", Convert.ToInt32(ddl_ctype.SelectedValue));
            if (ddl_seller.SelectedValue != "")
                where.AppendFormat(" and a.sellerid={0}", Convert.ToInt32(ddl_seller.SelectedValue));
            if (ddl_department.SelectedValue != "")
                where.AppendFormat(" and a.departmentItemId={0}", Convert.ToInt32(ddl_department.SelectedValue));
            return where.ToString();
        }

        /// <summary>
        /// 列表绑定的投诉情况
        /// </summary>
        private void rptBind()
        {
            DataSet ds = logic.complaint.select(strWhere(), "complaintDt desc", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_list.DataSource = ds.Tables[1];
            rpt_list.DataBind();
        }
        private void ddlBuyerBind()
        {
            DataTable dt = logic.company.listWithCompanyType("2");
            ddl_buyer.DataSource = dt;
            ddl_buyer.DataBind();
            ddl_buyer.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
        }
        private void ddlDepartmentBind()
        {
            DataTable dt = logic.departmentType.listWithAll();
            ddl_department.DataSource = dt;
            ddl_department.DataBind();
            ddl_department.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
        }
        private void ddlctNameBind()
        {
            DataTable dt = logic.complaintType.getByParentId(0);
            ddl_ctype.DataSource = dt;
            ddl_ctype.DataBind();
            ddl_ctype.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
        }
        private void ddlSellerBind()
        {
            DataTable dt = logic.company.listWithCompanyType("1");
            ddl_seller.DataSource = dt;
            ddl_seller.DataBind();
            ddl_seller.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
        }

        /// <summary>
        /// 当前列表导出Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbt_importall_Click(object sender, EventArgs e)
        {
            string TimeRange="";
            if (ext_StartInputDt.SelectedDate != DateTime.MinValue && ext_EndInputDt.SelectedDate != DateTime.MinValue)
            {
                TimeRange = ext_StartInputDt.SelectedDate.ToShortDateString() + "至" + ext_EndInputDt.SelectedDate.ToShortDateString();
            }
            else if (ext_StartInputDt.SelectedDate != DateTime.MinValue && ext_EndInputDt.SelectedDate == DateTime.MinValue)
            {
                TimeRange = ext_StartInputDt.SelectedDate.ToShortDateString() + "至—";
            }
            else if (ext_StartInputDt.SelectedDate == DateTime.MinValue && ext_EndInputDt.SelectedDate != DateTime.MinValue)
            {
                TimeRange = "—至" + ext_EndInputDt.SelectedDate.ToShortDateString();
            }
            else
            {
                TimeRange = "";
            }
            DataSet ds = logic.complaint.outputExcel(strWhere());
            DataTable dtlist = ds.Tables[0], dtcompany = ds.Tables[1], dtcomplaint = ds.Tables[2], dtcategory = ds.Tables[3], dtdepartment = ds.Tables[4];
            dtlist.Columns["complaintdt"].ColumnName = "日期";
            dtlist.Columns["buyername"].ColumnName = "客户名称";
            dtlist.Columns["productname"].ColumnName = "投诉产品";
            dtlist.Columns["complaintname"].ColumnName = "投诉类别";
            dtlist.Columns["department"].ColumnName = "责任部门";
            dtlist.Columns["responsibler"].ColumnName = "责任人";
            dtlist.Columns["sellername"].ColumnName = "责任供应商";
            dtlist.Columns["levelname"].ColumnName = "严重级别";
            dtlist.Columns["result"].ColumnName = "处理结果";
            dtlist.Columns["inputname"].ColumnName = "录入人";
            dtlist.Columns["remarks"].ColumnName = "投诉问题详情";
            dtlist.Columns.Remove("buyerid");
            dtlist.Columns.Remove("sellerid");
            ExportFacade facade = new ExportFacade();
            HSSFWorkbook workbook = facade.InitializeWorkbook("杭州农副产品物流网络有限公司", logic.sysAdmin.AdminID.ToString(), "采购配送系统", "投诉管理");
            Sheet sheet1 = workbook.CreateSheet("投诉详细");
            facade.CreateRowHeader(workbook, sheet1, TimeRange + " 投诉列表", dtlist);
            facade.FillRowData(workbook, sheet1, 2, dtlist, null, null, null, null);
            Sheet sheet2 = workbook.CreateSheet("客户投诉");
            facade.CreateRowHeader(workbook, sheet2, TimeRange + " 客户投诉情况", dtcompany);
            facade.FillRowData(workbook, sheet2, 2, dtcompany, null, null, null, null);
            Sheet sheet3 = workbook.CreateSheet("投诉汇总");
            facade.CreateRowHeader(workbook, sheet3, TimeRange + " 投诉问题汇总", dtcomplaint);
            facade.FillRowData(workbook, sheet3, 2, dtcomplaint, null, null, null, null);
            #region 小类投诉情况
            GraphPane graphpane = new GraphPane();
            graphpane.Title.Text = "小类投诉情况";
            graphpane.Title.FontSpec.Size = 12f;
            graphpane.XAxis.Title.Text = "小类";
            graphpane.XAxis.Title.FontSpec.Size = 11f;
            graphpane.YAxis.Title.Text = ChangeStr("投诉数量");
            graphpane.YAxis.Title.FontSpec.Angle = 90;
            graphpane.YAxis.Title.FontSpec.Size = 11f;
            graphpane.XAxis.IsVisible = true;
            graphpane.YAxis.IsVisible = true;
            List<string> category=new List<string>();
            List<double> cnum = new List<double>();
            int maxcnum = 2;
            foreach (DataRow dr in dtcategory.Rows)
            {
                if(Convert.ToInt32( dr[1].ToString())>maxcnum)
                    maxcnum=Convert.ToInt32( dr[1].ToString());
                category.Add(ChangeStr( dr[0].ToString()));
                cnum.Add(Convert.ToDouble(dr[1].ToString()));
            }
            
            BarItem baritem = graphpane.AddBar(null,null,cnum.ToArray(), Color.Red);
            baritem.Bar.Fill = new Fill(Color.Red, Color.White, Color.Red);
            BarItem.CreateBarLabels(graphpane, false, "f0");
            graphpane.XAxis.Scale.TextLabels = category.ToArray();
            graphpane.XAxis.Scale.Max = category.ToArray().Length+1;
            graphpane.XAxis.Scale.MajorStep = 1;
            graphpane.XAxis.MinorTic.Size = 0;
            graphpane.XAxis.MajorTic.Size = 0;
            graphpane.XAxis.Cross = 0;
            graphpane.XAxis.Scale.FontSpec.Size = 10f;
            graphpane.XAxis.Scale.FontSpec.Family = "宋体";
            graphpane.XAxis.Type = AxisType.Text;
            graphpane.XAxis.MajorTic.IsOutside = false;
            graphpane.XAxis.MajorTic.IsOpposite = false;
            graphpane.YAxis.Scale.Max = maxcnum+2;
            graphpane.YAxis.MinorTic.Size = 0;
            graphpane.YAxis.MinorGrid.DashOff = 0;
            graphpane.YAxis.Scale.MajorStep = 1;
            graphpane.YAxis.MajorTic.IsOpposite = false;
            graphpane.YAxis.MajorTic.IsOutside = false;
            graphpane.Chart.Fill = new Fill(Color.White, Color.FromArgb(255, 255, 166), 90F);
            graphpane.Fill = new Fill(Color.White, Color.FromArgb(250, 250, 255),45.0f);
            graphpane.Fill.IsScaled = true;
            MemoryStream ms = new MemoryStream();
            //zgc.GetImage().Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
            Bitmap map = graphpane.GetImage(750,550,17);
            map.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] picbyte = ms.ToArray();
            int index = workbook.AddPicture(picbyte, NPOI.SS.UserModel.PictureType.JPEG);
            Sheet sheet4 = workbook.CreateSheet("小类投诉");
            facade.CreateRowHeader(workbook, sheet4, TimeRange + " 小类投诉情况", dtcategory);
            facade.FillRowData(workbook, sheet4, 2, dtcategory, null, null, null, null);
            HSSFPatriarch hssfpatriarch = (HSSFPatriarch)sheet4.CreateDrawingPatriarch();
            HSSFClientAnchor hssfanchor = new HSSFClientAnchor(0, 0, 0, 0, 4, 1, 18, 28);
            HSSFPicture hssfpic = (HSSFPicture)hssfpatriarch.CreatePicture(hssfanchor, index);
            #endregion
            #region 部门投诉情况
            GraphPane gp2 = new GraphPane();
            gp2.Title.Text = "部门投诉情况";
            gp2.XAxis.IsVisible = false;
            gp2.YAxis.IsVisible = false;
            gp2.Title.FontSpec.Size = 12f;
            gp2.Fill = new Fill(Color.White);
            gp2.Chart.Fill.Type = FillType.None;
            gp2.Legend.Position = LegendPos.Float;
            gp2.Legend.Location = new Location(0.95f, 0.08f, CoordType.PaneFraction, AlignH.Right, AlignV.Top);
            gp2.Legend.FontSpec.Size = 10f;
            gp2.Legend.IsHStack = false;
            List<double> comnum=new List<double>();
            List<string> dname=new List<string>();
            foreach(DataRow dr in dtdepartment.Rows )
            {
                gp2.AddPieSlice(Convert.ToDouble(dr[1].ToString()), GetRandomColor(), 0, dr[0].ToString()+" ("+dr[1].ToString()+")").LabelType=PieLabelType.Percent;
            }
            Bitmap bitmap = gp2.GetImage(700, 700, 14);
            MemoryStream mstream = new MemoryStream();
            bitmap.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] buffer = mstream.ToArray();
            int picindex = workbook.AddPicture(buffer, NPOI.SS.UserModel.PictureType.JPEG);
            Sheet sheet5 = workbook.CreateSheet("部门投诉");
            facade.CreateRowHeader(workbook, sheet5, TimeRange + " 责任部门投诉情况", dtdepartment);
            facade.FillRowData(workbook, sheet5, 2, dtdepartment, null, null, null, null);
            HSSFPatriarch patriarch = (HSSFPatriarch)sheet5.CreateDrawingPatriarch();
            HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, 4, 1, 15, 34);
            HSSFPicture pic = (HSSFPicture)patriarch.CreatePicture(anchor, picindex);
            #endregion
            facade.ExportByWeb(workbook, TimeRange.ToString() + "采购配送系统投诉统计", TimeRange.ToString() + "采购配送系统投诉统计.xls");
            
        }
        private string ChangeStr(string str)
        {
            Char[] chars = str.ToCharArray();
            string returnstr = "";
            for (int i = 0; i < chars.Length;i++)
            {
                returnstr = returnstr + chars[i] + "\n";
            }
            return returnstr;
        }
        private Color GetRandomColor()
        {
            Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
            System.Threading.Thread.Sleep(RandomNum_First.Next(150));
            Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);
            System.Threading.Thread.Sleep(RandomNum_Sencond.Next(160));
            Random RandomNum_3 = new Random((int)DateTime.Now.Ticks);

            int int_Red = RandomNum_First.Next(250);
            int int_Green = RandomNum_Sencond.Next(250);
            int int_Blue = RandomNum_3.Next(250);
            // 为了在白色背景上显示，尽量生成深色
            //int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;
            //int_Blue = (int_Blue > 255) ? 255 : int_Blue;

            return Color.FromArgb(int_Red, int_Green, int_Blue);
        }

        protected void lbt_select_Click(object sender, EventArgs e)
        {
            rptBind();
        }
    }
}
